package com.keepers.repair;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.Utils;
import com.keepers.repair.helper.MediaPlayHelper;
import com.keepers.repair.helper.SpHelper;
import com.keepers.repair.net.HttpUtil;
import com.keepers.repair.net.LogUtil;
import com.keepers.repair.service.INotNetworkCallback;
import com.keepers.repair.service.IPlayCallback;
import com.keepers.repair.service.MsgSender;
import com.keepers.repair.service.MyRecParse;
import com.keepers.repair.service.NotifyReceiver;
import com.keepers.repair.tcp.ResponseCallback;
import com.keepers.repair.tcp.TCPClient;
import com.keepers.repair.utils.AlertToast;
import com.keepers.repair.utils.Api;
import com.keepers.repair.utils.CollectionUtil;
import com.keepers.repair.utils.ExtensionsKt;
import com.keepers.repair.utils.MsgType;
import com.keepers.repair.utils.UtilsKt;

import java.io.File;
import java.util.List;

/**
 * auth aboom
 * date 2018/10/21
 */
public class RepApplication extends Application {

    static         RepApplication      app;
    private static TCPClient           tcpClient;
    private        MediaPlayHelper     mediaPlayHelper;
    private        IPlayCallback       playCallback;
    private        INotNetworkCallback notNetworkCallback;


    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        Utils.init(this);
        AlertToast.init(this);
        Api.INSTANCE.setBaseUrl(ExtensionsKt.getServer(this).getUrl());
        registerScreenState();
//        registerConnectivityReceiver();// 注册系统发送的网络连接变化广播
//        tcpClient = TCPClient.build();
//        UnCeHandler unCeHandler = new UnCeHandler(this);
//        Thread.setDefaultUncaughtExceptionHandler(unCeHandler);
//        initPlay();
    }

    private void initPlay() {
        mediaPlayHelper = new MediaPlayHelper();
        mediaPlayHelper.setOnPlayListener((userName, playPath) -> {
            if (playCallback != null) {
                playCallback.onPlay(userName, playPath);
            }
        });
    }

    public static RepApplication getApp() {
        return app;
    }

    private NotifyReceiver mScreenReceiver = new NotifyReceiver();


    public void startConnectSocketServer() {
        initSocket();
    }

    private void initSocket() {
        if (tcpClient != null) {
            tcpClient.closeTcp();
        }
        if (SpHelper.getLoginUserInfo() == null) {
            return;
        }
        String currentHttpHost = SpHelper.getCurrentHttpHost();
        if (TextUtils.isEmpty(currentHttpHost)) {
            currentHttpHost = HttpUtil.HTTP_HOST;
        }
        tcpClient.server(currentHttpHost, 7000)
                .breath(new MsgSender("心跳", "Heart").parse(), 270 * 1000)
                .connTimeout(10 * 1000);
        tcpClient.onResponse(responseCallback);
    }

    private ResponseCallback responseCallback = new ResponseCallback() {
        @Override
        public void onRec() {
            MyRecParse myRecParse = new MyRecParse();
            List<String> parse = myRecParse.parse();
            if (CollectionUtil.isNotEmpty(parse)) {
                for (String msg : parse) {
                    playAudio(msg);
                }
            }
        }

        @Override
        public void onFail(Throwable throwable) {
            LogUtil.e("response handlerError:" + throwable.getMessage());
            if (UtilsKt.isNetworkConnected() && SpHelper.getLoginUserInfo() != null) {
                initSocket();
            }
        }
    };

    private synchronized void playAudio(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        JSONObject parseObject = JSONObject.parseObject(msg);
        String type = parseObject.getString("MType");
        if (MsgType.AUDIO.getValue().equals(type)) {
            String audio = parseObject.getString("Content");
            String name = parseObject.getString("FromUserName");
            if (!TextUtils.isEmpty(audio)) {
                String[] split = audio.split(File.separator);
                String fileName = split[split.length - 1];
                mediaPlayHelper.down(name, fileName);
            }
        }
    }


    public void sendMessage(String msg) {
        send(msg, "Text");
    }

    public void sendVoice(String path) {
        send(path, "Audio");
    }

    public void send(String message, String msgType) {
        if (!UtilsKt.isNetworkConnected()) {
            AlertToast.show("请检查网络");
            tcpClient.closeTcp();
            return;
        }
        byte[] parse = new MsgSender(message, msgType).parse();
        tcpClient.request(parse);
    }


    public void setPlayCallback(IPlayCallback playCallback) {
        this.playCallback = playCallback;
    }

    public void setNotNetworkCallback(INotNetworkCallback notNetworkCallback) {
        this.notNetworkCallback = notNetworkCallback;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void registerScreenState() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        registerReceiver(mScreenReceiver, filter);
    }

}
